package com.yejiarong.common.validate;

import com.yejiarong.common.validate.annotation.TimeTemplate;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @author YeJR
 */
public class TimeTemplateValidate  implements ConstraintValidator<TimeTemplate, String> {

    private String format;

    @Override
    public void initialize(TimeTemplate constraintAnnotation) {
        this.format = constraintAnnotation.format();
    }

    /**
     * Implements the validation logic.
     * The state of {@code value} must not be altered.
     * <p>
     * This method can be accessed concurrently, thread-safety must be ensured
     * by the implementation.
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (Objects.nonNull(value) && !value.trim().isEmpty()) {
            try {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
                simpleDateFormat.setLenient(false);
                Date date = simpleDateFormat.parse(value);
                String format = simpleDateFormat.format(date);
                return format.equals(value);
            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }
}
